/*
 * @lc app=leetcode.cn id=692 lang=typescript
 *
 * [692] 前K个高频单词
 */

// @lc code=start
function topKFrequent(words: string[], k: number): string[] {
  const hash: Map<string, number> = new Map();

  for (let word of words) {
    hash.set(word, (hash.get(word) || 0) + 1);
  }

  let result = Array.from(hash.entries());
  result.sort((b, a) => {
    if (a[1] < b[1]) {
      return -1;
    } else if (a[1] > b[1]) {
      return 1;
    } else {
      if (a[0] > b[0]) {
        return -1;
      } else if (a[0] < b[0]) {
        return 1;
      } else {
        return 0;
      }
    }
  });

  return result.slice(0, k).map((val) => val[0]);
}
// @lc code=end
